<?php
namespace Client\Controller;
use Think\Controller;
class WxController extends Controller {
	
	public static $wx;         //缓存微信对象
	public static $wx_openid;  //缓存微信对象
	public static $usertable;  //用户表
	public static $userset;		//用户积分设置
	
	public function __construct($options){
		
		self::$usertable=M('weixin_client_user');
		
		$options['appid']=C('BB_APPID_client');
		$options['secret']=C('BB_SECRET_client');
		$options['token']=C('BB_TOKEN');
		self::$wx=new \bb\Wechat($options);
		
		//===========================
		self::$userset=M('bb_user_set')->find();
		//==============
		//判断验证模式
		if(IS_GET){
			self::$wx->valid();
		}else{
			if(!self::$wx->valid()){die('no access!!!');}
			$data=self::$wx->request();
			
			//self::$wx->response("本系统暂时无法识别您的指令！",'text');
			//==调试信息====================================
			
			//foreach($data as $k=>$v){
			//	$str=$str.$k."=>".$v.'  ';
			//}
			//file_put_contents('aaa.txt','收到请求:'.date('Y-m-d H:i:s').PHP_EOL.'通知信息:'.$str.PHP_EOL.PHP_EOL.PHP_EOL,FILE_APPEND);
			
			//==调试信息====================================
			self::$wx_openid=$data['fromusername'];
			//==和公众号有交互的时候更新用户信息=====================================================
			if($data['msgtype']!='event' || ($data['event']!='LOCATION' &&  $data['event']!='TEMPLATESENDJOBFINISH')){ //不要在更新坐标和发送模板消息的时候更新用户
				$user=self::$usertable->where(array('openid'=>self::$wx_openid))->find();
				if($user){
					$userdata=self::$wx->user(self::$wx_openid);
					$userdata['id']=$user['id'];
					self::$usertable->save($userdata);
					unset($user,$userdata);
				}
			}
			//=====================================================================
			switch($data['msgtype']){
				case 'text':
					$this->checkKeyword($data['content'],$data);
					break;
				case $data['msgtype']=='image' || $data['msgtype']=='voice' || $data['msgtype']=='video' || $data['msgtype']=='shortvideo' || $data['msgtype']=='location' || $data['msgtype']=='link':
					$this->checkKeyMedia($data);
					break;
				case 'event':
					$this->checkEvent($data);
					break;
				default:
					self::$wx->response("本系统暂时无法识别您的指令！",'text');
			}
		}
	}
	//默认页面
	public function index(){
		
		
	}
	//文本消息
	public function checkKeyword($Keyword,$request){
		$m=M('weixin_keyword');
		$news=M('weixin_news');
		$message=M('weixin_message');
		$data=$m->where(array('keyword'=>$Keyword,'wx_id'=>1))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			if($Keyword=='开店'){
				$u=M('bb_agent')->where(array('openid'=>self::$wx_openid))->find();
				if($u){
					$array[0]['Title']='去录入店铺';
					$array[0]['Description']='';
					$array[0]['PicUrl']='http://wx.tingzan88.com/Public/business/img/home.jpg';
					$array[0]['Url']='http://wx.tingzan88.com/Client/Kehu/addkehu';
					self::$wx->response($array,'news');
				}else{
					self::$wx->response("no",'text');
				}
			}else{
				$re=$message->add($request);
			}
			self::$wx->response("no",'text');
		}
	}
		
	//事件消息
	public function checkEvent($data){
		switch($data['event']){
			//关注
			case 'subscribe':
				if($data['eventkey']){
					//扫码关注
					$this->checksmsubscribe($data['eventkey'],$data['ticket']);
				}else{
					//关注
					$this->checksubscribe();
				}
				break;
			//取消关注
			case 'unsubscribe':
				$this->checkunsubscribe();
				break;
			//关注后扫码
			case 'SCAN':
				$this->checkscan($data['eventkey'],$data['ticket']);
				break;
			//上报用户地理位置
			case 'LOCATION':
				$this->checklocation($data['latitude'],$data['longitude'],$data['precision']);
				break;
			//自定义菜单事件命令
			case 'CLICK':
				$this->checkCLICK($data['eventkey']);
				break;
			//自定义菜单事件打开网页
			case 'VIEW':
				$this->checkVIEW($data['eventkey']);
				break;
			default:
				self::$wx->response("本系统暂时无法识别你的事件 ！",'text');
		}
	}
	//关注公众号
	public function checksubscribe(){
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$userdata=self::$wx->user(self::$wx_openid);
			$userdata['id']=$user['id'];
			$m->save($userdata);
		}else{
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
		$keym=M('weixin_keyword');
		$news=M('weixin_news');
		$data=$keym->where(array('keyword'=>"首次关注"))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("no",'text');
		}
		
		self::$wx->response("感谢您的关注！".$data['id'],'text');
	}
	
	//扫描2微码关注公众号
	public function checksmsubscribe($eventkey,$ticket){
		//获取2维码的参数=============
		$m=self::$usertable;
		$wx_user=$m->where(array('openid'=>self::$wx_openid))->find();
		//找不到用户就写入用户信息
		if(!$wx_user){
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
		//判断用户是否获取
		if(!$userdata){
			$userdata=self::$wx->user(self::$wx_openid);
		}
		//是否有关键词
		if($eventkey){
			$eventkey=substr($eventkey,8);
			//扫描店铺2维码
			if(substr($eventkey,0,5)=='shop_'){
				$client_user=M('client_user')->where(array('openid'=>self::$wx_openid))->find();
				if(!$client_user){
					$u=$userdata;
					$c_u['openid']=self::$wx_openid;
					$c_u['username']=$u['nickname'];
					if($u['sex']==1){$sex='男';}elseif($u['sex']==2){$sex='女';}else{$sex=' '; }
					$c_u['sex']=$sex;
					if(self::$userset['isgift']) {
						$c_u['integral']=self::$userset['reg_score'];
					}
					M('client_user')->add($c_u);
					//=====================
					//赠送操作
					if (self::$userset['isgift']) {
						$gift=explode(",", self::$userset['gift_detail']);
						if($gift[1]){
							$cardnopwd = $this->getCardNoPwd();
							$data_card['type']=$gift[0];
							$data_card['openid']=self::$wx_openid;
							$data_card['money']=$gift[1];
							$data_card['usemoney']=$gift[3];
							$data_card['cardno']=$cardnopwd['no'];
							$data_card['cardpwd']=$cardnopwd['pwd'];
							$data_card['status']=1;
							$data_card['stime']=$data_card['ctime']=time();
							$data_card['etime']=time()+$gift[2]*24*60*60;
							$rcard=M('bb_user_card')->add($data_card);	
							
							$log['openid']=self::$wx_openid;
							$log['type']='2';   //抵用券
							$log['addtime']=time();   
							$log['msg']='首次注册送抵用劵 '.$gift[1].'元，满'.$gift[3].'元使用！';
							M('log_msg')->add($log);
						}
						
						$log['openid']=self::$wx_openid;
						$log['type']='1';   //积分日志
						$log['addtime']=time();   
						$log['msg']='积分增加：首次注册送'.self::$userset['reg_score'].'个积分';
						M('log_msg')->add($log);
					}
					//=====================
				}
				//============================
				$shopid='shop'.$eventkey;		//组合店铺ID
				$shopuser=M('bb_shop_user')->where(array('user_openid'=>self::$wx_openid,'shopid'=>$shopid))->find();
				if(!$shopuser){
					M('bb_shop_user')->add(array('user_openid'=>self::$wx_openid,'shopid'=>$shopid));
				}
			
			}elseif(substr($eventkey,0,5)=='user_'){
				$eventkey = substr($eventkey,5);
			//扫描用户2维码
				$client_user=M('client_user')->where(array('openid'=>self::$wx_openid))->find();
				if(!$client_user){
					$p_user=M('client_user')->where(array('id'=>$eventkey))->find();
					$u=$userdata;
					$c_u['openid']=self::$wx_openid;
					$c_u['username']=$u['nickname'];
					if($u['sex']==1){$sex='男';}elseif($u['sex']==2){$sex='女';}else{$sex=' '; }
					$c_u['sex']=$sex;
					if(self::$userset['isgift']) {
						$c_u['integral']=self::$userset['reg_score'];
					}
					$c_u['pid']=$p_user['id'];
					$c_u['path']=$p_user['path'].','.$p_user['id'];
					M('client_user')->add($c_u);
					//=推荐好友赠送积分========================
					$p_user['integral']=($p_user['integral']+self::$userset['quote_score']);	
					M('client_user')->save($p_user);
					//=====================
					//赠送操作
					if (self::$userset['isgift']) {
						$gift=explode(",", self::$userset['gift_detail']);
						if($gift[1]){
							$cardnopwd = $this->getCardNoPwd();
							$data_card['type']=$gift[0];
							$data_card['openid']=self::$wx_openid;
							$data_card['money']=$gift[1];
							$data_card['usemoney']=$gift[3];
							$data_card['cardno']=$cardnopwd['no'];
							$data_card['cardpwd']=$cardnopwd['pwd'];
							$data_card['status']=1;
							$data_card['stime']=$data_card['ctime']=time();
							$data_card['etime']=time()+$gift[2]*24*60*60;
							$rcard=M('bb_user_card')->add($data_card);	
							
							$log['openid']=self::$wx_openid;
							$log['type']='2';   //抵用券
							$log['addtime']=time();   
							$log['msg']='首次注册送抵用劵 '.$gift[1].'元，满'.$gift[3].'元使用！';
							M('log_msg')->add($log);
						}
						
						$log['openid']=self::$wx_openid;
						$log['type']='1';   //积分日志
						$log['addtime']=time();   
						$log['msg']='积分增加：首次注册送'.self::$userset['reg_score'].'个积分';
						M('log_msg')->add($log);
					}
					//=====================
				}
			}
		}
		//============================
		//首次关注发送首次关注关键词
		$keym=M('weixin_keyword');
		$news=M('weixin_news');
		$data=$keym->where(array('keyword'=>"首次关注"))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}
		//==================================
	}
	//关注过扫码
	public function checkscan($eventkey,$ticket){
		$m=self::$usertable;
		$wx_user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($wx_user){
			$userdata=self::$wx->user(self::$wx_openid);
			$userdata['id']=$wx_user['id'];
			$m->save($userdata);
		}else{
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
		//获取2维码的参数=============			
		if($eventkey){
			//店铺二维码
			if(substr($eventkey,0,5)=='shop_'){
				$eventkey=substr($eventkey,5);
				//================================
				$client_user=M('client_user')->where(array('openid'=>self::$wx_openid))->find();
				if(!$client_user){
					$u=$userdata;
					$c_u['openid']=self::$wx_openid;
					$c_u['username']=$u['nickname'];
					if($u['sex']==1){$sex='男';}elseif($u['sex']==2){$sex='女';}else{$sex=' '; }
					$c_u['sex']=$sex;
					if(self::$userset['isgift']) {
						$c_u['integral']=self::$userset['reg_score'];
					}
					M('client_user')->add($c_u);
					//=====================
					//赠送操作
					if (self::$userset['isgift']) {
						$gift=explode(",", self::$userset['gift_detail']);
						if($gift[1]){
							$cardnopwd = $this->getCardNoPwd();
							$data_card['type']=$gift[0];
							$data_card['openid']=self::$wx_openid;
							$data_card['money']=$gift[1];
							$data_card['usemoney']=$gift[3];
							$data_card['cardno']=$cardnopwd['no'];
							$data_card['cardpwd']=$cardnopwd['pwd'];
							$data_card['status']=1;
							$data_card['stime']=$data_card['ctime']=time();
							$data_card['etime']=time()+$gift[2]*24*60*60;
							$rcard=M('bb_user_card')->add($data_card);	
							
							$log['openid']=self::$wx_openid;
							$log['type']='2';   //抵用券
							$log['addtime']=time();   
							$log['msg']='首次注册送抵用劵 '.$gift[1].'元，满'.$gift[3].'元使用！';
							M('log_msg')->add($log);
						}
						
						$log['openid']=self::$wx_openid;
						$log['type']='1';   //积分日志
						$log['addtime']=time();   
						$log['msg']='积分增加：首次注册送'.self::$userset['reg_score'].'个积分';
						M('log_msg')->add($log);
					}
					//=====================
				}
				//============================
				$shopid='shop'.$eventkey;		//组合店铺ID
				$shopuser=M('bb_shop_user')->where(array('user_openid'=>self::$wx_openid,'shopid'=>$shopid))->find();
				if(!$shopuser){
					M('bb_shop_user')->add(array('user_openid'=>self::$wx_openid,'shopid'=>$shopid));
				}
				//=========================
			}elseif(substr($eventkey,0,5)=='user_'){
				$eventkey = substr($eventkey,5);
				$client_user=M('client_user')->where(array('openid'=>self::$wx_openid))->find();
				if(!$client_user){
					$p_user=M('client_user')->where(array('id'=>$eventkey))->find();
					$u=$userdata;
					$c_u['openid']=self::$wx_openid;
					$c_u['username']=$u['nickname'];
					if($u['sex']==1){$sex='男';}elseif($u['sex']==2){$sex='女';}else{$sex=' '; }
					$c_u['sex']=$sex;
					if(self::$userset['isgift']) {
						$c_u['integral']=self::$userset['reg_score'];
					}
					$c_u['pid']=$p_user['id'];
					$c_u['path']=$p_user['path'].','.$p_user['id'];
					M('client_user')->add($c_u);
					//=推荐好友赠送积分========================
					$p_user['integral']=($p_user['integral']+self::$userset['quote_score']);	
					M('client_user')->save($p_user);
					//=====================
					//=====================
					//赠送操作
					if (self::$userset['isgift']) {
						$gift=explode(",", self::$userset['gift_detail']);
						if($gift[1]){
							$cardnopwd = $this->getCardNoPwd();
							$data_card['type']=$gift[0];
							$data_card['openid']=self::$wx_openid;
							$data_card['money']=$gift[1];
							$data_card['usemoney']=$gift[3];
							$data_card['cardno']=$cardnopwd['no'];
							$data_card['cardpwd']=$cardnopwd['pwd'];
							$data_card['status']=1;
							$data_card['stime']=$data_card['ctime']=time();
							$data_card['etime']=time()+$gift[2]*24*60*60;
							$rcard=M('bb_user_card')->add($data_card);	
							
							$log['openid']=self::$wx_openid;
							$log['type']='2';   //抵用券
							$log['addtime']=time();   
							$log['msg']='首次注册送抵用劵 '.$gift[1].'元，满'.$gift[3].'元使用！';
							M('log_msg')->add($log);
						}
						
						$log['openid']=self::$wx_openid;
						$log['type']='1';   //积分日志
						$log['addtime']=time();   
						$log['msg']='积分增加：首次注册送'.self::$userset['reg_score'].'个积分';
						M('log_msg')->add($log);
					}
					//=====================
				}
			}
		}
	}
	//自定义菜单事件命令
	public function checkCLICK($eventkey){
		$m=M('weixin_keyword');
		$news=M('weixin_news');
		$message=M('weixin_message');
		$data=$m->where(array('keyword'=>$eventkey))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("no",'text');
		}
		
	}
	
	//自定义菜单事件打开网页
	public function checkVIEW($eventkey){
		//微信会打开这个网址$eventkey
	}
	
	//用户地理位置
	public function checklocation($latitude,$longitude,$precision){
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$url = "http://api.map.baidu.com/geoconv/v1/?coords=".$longitude.",".$latitude."&from=1&to=5&ak=".C('BB_AK');
	 		$re = get_curl($url);
			$zb = json_decode($re,true);
			if($zb['status']==0){
				$userdata['longitude']=$zb['result']['0']['x'];
				$userdata['latitude']=$zb['result']['0']['y'];
				$userdata['id']=$user['id'];
				$m->save($userdata);		//更新用户位置坐标。
				//self::$wx->response('坐标更新了！','text');
			}else{
				//self::$wx->response($zb['status'],'text');
				//self::$wx->sendMsg('oY8X0s9aYANqYI3ETXPnlKYcDS4o',$zb['status'],'text');
			}
		}
	}
	
	//==多媒体资料处理=======================================================
	public function checkKeyMedia($data){
		$message=M('weixin_message');
		switch($data['msgtype']){
			//用户发来照片
			case 'image':
				$path=self::$wx->download_medis($data['mediaid']);	//下载图片到本地
				$data['content']=$path;
				break;
			//用户发来语音
			case 'voice':
				$data['content']=$data['recongnition'];				//语音识别结果
				break;
			//用户发来视频
			case 'video':
				//暂不处理
				break;
			//用户发来小视频
			case 'shortvideo':
				//暂不处理
				break;
			//用户发来地理位置
			case 'location':
				//暂不处理
				break;
			//用户发来链接
			case 'link':
				//暂不处理
				break;
			default:
				self::$wx->response("本系统暂时无法识别您的指令！",'text');
		}
		
        $re=$message->add($data);
		self::$wx->response("no",'text');
	}
	//取消关注公众号
	public function checkunsubscribe(){
		$m=self::$usertable;
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		$m->delete($user['id']);		//删除取消关注的会员
	}
	
	//遍历微信图文回复数据
	public function newsbl($data){
		foreach ($data as $k => $v) {
			$img=$this->getPic($v['img']);
			$array[$k]['Title']=$v['title'];
			$array[$k]['Description']=$v['info'];
			$array[$k]['PicUrl']=$img['imgurl'];
			$array[$k]['Url']=htmlspecialchars_decode($v['url']);
		}
		return $array;
	}
	//获取单张图片地址
	public function getPic($id){
		$m=M('weixin_upload_img');
		$map['id']=$id;
		$list=$m->where($map)->find();
		if($list){
			$list['imgurl']=C('BB_URL')."/Upload/".$list['savepath'].$list['savename'];
		}
		return $list?$list:"";
	}
	
	
	public function getCardNoPwd(){  
		$dict_no = "0123456789";
		$length_no = 10;
		$dict_pwd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$length_pwd = 10;
		$card['no'] = "";
		$card['pwd'] = "";
		for($i=0;$i<$length_no;$i++){    $card['no'].=$dict_no[rand(0,(strlen($dict_no)-1))];    } 
		for($i=0;$i<$length_pwd;$i++){    $card['pwd'].=$dict_pwd[rand(0,(strlen($dict_pwd)-1))];    }   
		return $card;
	}
}